package com.ddstation.crm.login.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONObject;
import com.ddstation.crm.login.util.ValidateUtil;
import com.ddstation.crm.menu.entity.DtInvsManageInstitutionMenuEntity;
import com.ddstation.crm.menu.mapper.DtInvsManageInstitutionMenuMapper;
import com.ddstation.crm.menu.service.MENU_FILTER_ENUM;
import com.ddstation.crm.menu.service.MenuService;
import com.ddstation.crm.organization_structure.mapper.DtInvsOrganizationStructureMapper;
import com.ddstation.crud.entity.DtInvsLoginIpEntity;
import com.ddstation.crud.mapper.DtInvsLoginIpMapper;
import com.ddstation.crud.mapper.DtInvsSupervisorMapper;
import com.ddstation.security.property.SignatureProperties;
import com.ddstation.security.util.MD5Util;
import com.ddstation.verifycode.entity.VerifycodeEntity;
import com.ddstation.verifycode.property.VerifyCodeProperties;
import com.ddstation.verifycode.service.VerifycodeService;

import com.sun.org.apache.bcel.internal.generic.NEW;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ddstation.crm.login.bean.SessionLoginData;
import com.ddstation.crud.entity.DtInvsManageInstitutionEntity;
import com.ddstation.crud.entity.DtInvsManageInstitutionSupervisorEntity;
import com.ddstation.crud.mapper.DtInvsManageInstitutionMapper;
import com.ddstation.crud.mapper.DtInvsManageInstitutionSupervisorMapper;


/**
 * 《卫监系统》 登录
 * @author zhengXiaoBin
 * @date 2019年7月26日
 */
@Controller
public class LoginController {

	/**
	 * 登录
	 * @param timeout
	 * @param model
	 * @return
	 */
	@RequestMapping(value={"/display"})
	public String comprehensiveDisplay(
			@RequestParam(required=false) Object timeout, // 超时 重新login
			Model model) {

		// 超时 重新login
		if (timeout != null) {
			model.addAttribute("timeout", timeout);
		}

		return "pc/comprehensive_display/comprehensive_display";
	}
	
	/**
	 * 登录
	 * @param timeout
	 * @param model
	 * @return
	 */
	@RequestMapping(value={"/login"})
	public String initLoginEvent(
			@RequestParam(required=false) Object timeout, // 超时 重新login
			Model model) {

		// 超时 重新login
		if (timeout != null) {
			model.addAttribute("timeout", timeout);
		}

		return "login/login";
	}

	@RequestMapping(value="invs_weknowhealth/login", method=RequestMethod.POST)
	public @ResponseBody Map<String, Object> doLoginEvent(
			@RequestParam String loginUser,
			@RequestParam String loginPassword,
			@RequestParam String verifyInfo,
			HttpServletRequest request,
			HttpServletResponse response,
			HttpSession session) {

		Map<String, Object> ret = new HashMap<String, Object>();

		try {
			DtInvsManageInstitutionSupervisorEntity doctor = new DtInvsManageInstitutionSupervisorEntity();
			String newLoginUser = "invs_"+loginUser;
			doctor.setLoginUser(newLoginUser);
			doctor.setLoginPassword(loginPassword);
			doctor = dtInvsManageInstitutionSupervisorMapper.selectByLoginUser(doctor);

			if (doctor == null) { // 用户名密码不匹配
				ret.put("errorcode", -1);
				ret.put("errormsg", "用户名or密码不正确");
				return ret;
			}

			//登录IP校验
			String ip = ValidateUtil.getIpAddress(request);
			logger.debug("当前登录IP:"+ip);
			if(StringUtils.isEmpty(ip)) {
				ret.put("errorcode", -1);
				ret.put("errormsg", "登录IP异常");
				return ret;
			}

			DtInvsLoginIpEntity loginIp = new DtInvsLoginIpEntity();
			if(!ip.equals("127.0.0.1") && !ip.startsWith("192.168.") && ip.indexOf("0:0:0:0:") == -1) {
				loginIp = dtInvsLoginIpMapper.selectByLoginIp(null, ip);
			}

			//发送短信
			if(loginIp == null && StringUtils.isEmpty(verifyInfo)) {
				ret.put("errorcode", -1);
				ret.put("errormsg", "需要短信认证");
				ret.put("distrust", 1);
				return ret;
			}
			else {
				//短信校验
				if(loginIp == null && !StringUtils.isEmpty(verifyInfo)) {
					VerifycodeEntity verifycodeEntity = JSONObject.parseObject(verifyInfo, VerifycodeEntity.class);
					Integer checkRet = verifycode(verifycodeEntity.getPhone(), verifycodeEntity.getCode(), verifycodeEntity.getTimelimit(), verifycodeEntity.getDatasign());
					if ( checkRet != 0  ){
						ret.put("errorcode", checkRet);
						if(checkRet == -1) {
							ret.put("errormsg", "验证码错误");
						}
						else if(checkRet == -2) {
							ret.put("errormsg", "验证码失效");
						}
						return ret;
					}
				}

				// 用户身份验证ok
				// session中已经存在账号信息
				if (session != null && session.getId() != null) {
					SessionLoginData _loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY);
					if (_loginData != null && _loginData.getDoctor() != null) {
						if (!newLoginUser.equals(_loginData.getDoctor().getLoginUser())) { // session中已经存在的账号和现在登录的账号不同
							ret.put("errorcode", -1);
							ret.put("errormsg", "1台电脑只能允许登录1个账号");
							return ret;
						}
					}
				}

				// 机构信息
				DtInvsManageInstitutionEntity institution = dtInvsManageInstitutionMapper.selectByPrimaryKey(doctor.getInstitutionId());

				//权限菜单
				String institutionId = institution.getId();
				Integer supervisorId = doctor.getSupervisorId();
				Byte authType = doctor.getAuthType();
				List<DtInvsManageInstitutionMenuEntity> verticalMenu = menuService.getVerticalMenu(institutionId, supervisorId, authType, MENU_FILTER_ENUM.INSTITUTION_AND_DOCTOR);
				if(verticalMenu == null){
					ret.put("errorcode", -1);
					ret.put("errormsg", "此账号没有任何操作权限，请联系管理员。");
					return ret;
				}

				//获取身份
				int isManager = dtInvsOrganizationStructureMapper.selectIsManager(institutionId, supervisorId);
				int orgId = dtInvsOrganizationStructureMapper.selectOrgId(institutionId, supervisorId);

				// 登录信息session保存
				SessionLoginData loginData = new SessionLoginData();
				loginData.setDoctor(doctor);
				loginData.setInstitution(institution);
				loginData.setJurisdictionMenus(verticalMenu);
				loginData.setIsManager(isManager);
				loginData.setOrgId(orgId);

				//工作台session保存
				SessionLoginData workbenchData = new SessionLoginData();
				List<DtInvsManageInstitutionMenuEntity> workbenchVM = menuService.getWorkbenchVerticalMenu();
				loginData.setWorkbenchMenus(workbenchVM);

				session.setAttribute(SessionLoginData.KEY, loginData);

				//获取首个权限页面
				if(verticalMenu != null && verticalMenu.size() > 0){
					ret.put("toUrl", getUrl(verticalMenu.get(0).getUrl()));
				}else{
					ret.put("toUrl", "invs_home_page.do");//无权限异常页面,暂无页面默认第一个菜单页
				}

				ret.put("errorcode", 0);
			}
		} catch (Exception e) {
			ret.put("errorcode", -1);
			ret.put("errormsg", "登录异常");
		}
		return ret;
	}

	@RequestMapping(value="invs_weknowhealth/smscode_login", method=RequestMethod.POST)
	public @ResponseBody Map<String, Object> smscodeLogin(
			@RequestParam String loginUser,
			@RequestParam String loginPassword,
			@RequestParam String phonenum,
			HttpSession session) {

		Map<String, Object> ret = new HashMap<String, Object>();

		try {
			String msg = "获取短信验证码失败";

			if (StringUtils.isEmpty(phonenum)) {
				throw new Exception(msg);
			}

			DtInvsManageInstitutionSupervisorEntity doctor = new DtInvsManageInstitutionSupervisorEntity();
			String newLoginUser = "invs_"+loginUser;
			doctor.setLoginUser(newLoginUser);
			doctor.setLoginPassword(loginPassword);
			doctor = dtInvsManageInstitutionSupervisorMapper.selectByLoginUser(doctor);

			if (doctor == null) {
				throw new Exception(msg);
			}

			if (dtInvsSupervisorMapper.selectManagePhonenum(phonenum) == 0) {
				throw new Exception(msg);
			}

			VerifycodeEntity retEntity = verifycodeService.create(phonenum, VerifyCodeProperties.VERIFY_CODE_EXPIRES_SHORTMESSAGE * 60);
			/*VerifycodeEntity retEntity = new VerifycodeEntity();
			retEntity.setPhone(phonenum);
			retEntity.setDatasign(MD5Util.md5Encode("6528" + "15158110282" + Long.valueOf("4102416000000") + SignatureProperties.SECRET_KEY));
			retEntity.setTimelimit(Long.valueOf("4102416000000"));
			logger.debug(retEntity.toString());
			if(retEntity == null) {
				throw new Exception(msg);
			}*/

			ret.put("v", retEntity);
			ret.put("errorcode", 0);

		} catch (Exception e) {
			ret.put("errorcode", -1);
			ret.put("errormsg", e.getMessage());
		}
		return ret;
	}

	public String getUrl(String id){
		switch (id){
			case "institutionReview":
				return "invs_home_page.do";
			case "institutionAutonomy":
				return "invs_institution_autonomy.do";
			case "industryAutonomy":
				return "invs_industry_autonomy.do";
			case "governmentVision":
				return "invs_government_vision.do";
			case "societyVision":
				return "invs_society_vision.do";
			case "feedback":
				return "invs_feedback.do";
			case "warningHandle":
				return "invs_warning_handle.do";
			case "decisionAnalysis":
				return "invs_decision_analysis.do";
			case "systemSetting":
				return "invs_system_setting.do";
		}
		return "invs_home_page.do";//异常页面,暂无页面默认第一个菜单页
	}

	/**
	 * 注销用户
	 * @param session
	 * @return
	 */
	@RequestMapping(value="/logout")
	public String logoutEvent(HttpSession session) {
		if (session != null && session.getId() != null) {
//			session.invalidate();
			try {
				session.removeAttribute(SessionLoginData.KEY);
			} catch(Exception e) {
				e.printStackTrace();
			}
		}
//		return "login/login";
		return "pc/comprehensive_display/comprehensive_display";
	}


	/**
	 * IP未授权 短信验证
	 *
	 * @return   0:正常返回
	 *           -1:验证码不正确
	 *           -2:验证码失效
	 */
	private int verifycode(String phone,
						   String code,
						   Long timelimit,
						   String datasign){

		if (org.apache.commons.lang3.StringUtils.isBlank(phone) ||
				org.apache.commons.lang3.StringUtils.isBlank(code) ||
				timelimit == null ||
				org.apache.commons.lang3.StringUtils.isBlank(datasign)) {
			return -1;// 验证码不正确
		} else {
			if (timelimit < System.currentTimeMillis()) {
				return -2; // 验证码失效
			} else {
				VerifycodeEntity v = new VerifycodeEntity();
				v.setCode(code);
				v.setPhone(phone);
				v.setTimelimit(timelimit);
				v.setDatasign(datasign);
				if (!verifycodeService.validate(v)) {
					return  -1; // 验证码不正确
				}
			}
		}

		return 0;
	}

	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	private @Inject MenuService menuService = null;
	private @Inject
    DtInvsOrganizationStructureMapper dtInvsOrganizationStructureMapper;
	private @Inject DtInvsManageInstitutionMapper dtInvsManageInstitutionMapper;
	private @Inject DtInvsManageInstitutionSupervisorMapper dtInvsManageInstitutionSupervisorMapper;

	private @Inject DtInvsLoginIpMapper dtInvsLoginIpMapper;
	private @Inject VerifycodeService verifycodeService = null;
	private @Inject DtInvsSupervisorMapper dtInvsSupervisorMapper;
}
